package com.krt.facenettydemo;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.telpo.tps550.api.idcard.IdCard;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * @author hyj
 * @time 2019/10/12 9:31
 * @class describe
 */
public class UpdService extends Service {

    private DatagramSocket socket;
    private static final int PhonePort = 9999;//手机端口号
    private DatagramPacket packet;
    private volatile boolean stopReceiver = false;
    String filePath = "/sdcard/AIUI/devices.txt";
    public static Handler UpdFileHandler;
    private String path = Environment.getExternalStorageDirectory() + File.separator + "facePic" + File.separator + System.currentTimeMillis() + ".jpg";

    public static void setUpdFileHandler(Handler handler) {
        UpdFileHandler = handler;
    }

    private void receiveMessage() {
        new Thread() {
            public void run() {
                try {
                    socket = new DatagramSocket(PhonePort);
                } catch (SocketException e) {
                    e.printStackTrace();
                    LogUtils.eTag("upd", "socket异常");
                }
                byte[] receBuf = new byte[2048];
                packet = new DatagramPacket(receBuf, receBuf.length);
                while (!stopReceiver) {
                    try {
                        socket.receive(packet);
//                        final String receive = new String(packet.getData(), 0, packet.getLength(), "utf-8");
                        byte[] data = packet.getData();
                        Log.e("hyj", "服务收到UPD内容：" + data.length);
                        saveUpd(data);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        receiveMessage();
    }

    @SuppressLint("CheckResult")
    public void saveUpd(final byte[] data) {
        Observable.create(new ObservableOnSubscribe<Bitmap>() {

            @Override
            public void subscribe(ObservableEmitter<Bitmap> e) throws Exception {
                Bitmap bmp = new IdCard(UpdService.this).decodeIdCardImageOverseas(data);
                e.onNext(bmp);
                e.onComplete();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(bitmap -> {
                    if (UpdFileHandler != null) {
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj = bitmap;
                        UpdFileHandler.sendMessage(msg);
                    }
                });

//                .map(new Function<Bitmap, File>() {
//                    @Override
//                    public File apply(Bitmap bmp) throws Exception {
//                        File filePath = new File(path);
//                        if (!filePath.exists()) {
//                            filePath.getParentFile().mkdirs();
//                            FileOutputStream out = null;
//                            try {
//                                out = new FileOutputStream(filePath);
//                                bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
//                                out.flush();
//                                out.close();
//                            } catch (FileNotFoundException e) {
//                                e.printStackTrace();
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            }
//                        }
//                        return filePath;
//                    }
//                }).subscribeOn(Schedulers.io())
//        .observeOn(AndroidSchedulers.mainThread())
//        .subscribe(new Consumer<File>() {
//            @Override
//            public void accept(File file) throws Exception {
//                if (UpdFileHandler != null) {
//                    Message msg = new Message();
//                    msg.what = 1;
//                    msg.obj = file.getAbsoluteFile();
//                    UpdFileHandler.sendMessage(msg);
//                    LogUtils.eTag("UpdFileHandler", "发送接收到文件消息" + file.getAbsoluteFile());
//                }
//            }
//        });


    }

}
